<?php
class Advego_Report
{
	private $_savePath;

	/**
	 * @return the $_savePath
	 */
	public function getSavePath()
	{
		return $this->_savePath;
	}

	/**
	 * @param field_type $_savePath
	 */
	public function setSavePath( $savePath )
	{
		if ( !file_exists( $savePath ) )
		{
			mkdir( $savePath );
		}
		$this->_savePath = $savePath;
	}

	public function __construct( $subDir )
	{
		$config = Zend_Registry::get( 'config' );
		$this->setSavePath( $config->get( 'save_dir' ) . DIRECTORY_SEPARATOR . $subDir );
	}

	public function save( array $data )
	{
		$title = $data[ 'title' ];

		$tmp = '';
		$tmp .= "URL\r\n{URL}" . "\r\n\r\n";
		$tmp .= "Заголовок\r\n{TITLE}" . "\r\n\r\n";
		$tmp .= "Описание\r\n{DESC}" . "\r\n\r\n";
		$tmp .= "Полное описание\r\n{FULL_DESC}";

		$search = array( '{URL}', '{TITLE}', '{DESC}', '{FULL_DESC}' );
		$replace = array(
			$data[ 'link' ],
			$data[ 'title' ],
			$data[ 'desc' ],
			$data[ 'fullDesc' ] );
		$data = str_replace( $search, $replace, $tmp );

		$filename = $this->_makeFilename( $title );
		file_put_contents( $filename, $data );

		return $filename;
	}

	private function _makeFilename( $title )
	{
		assert( !empty( $title ) );
		$result = clean_filename( $title );
		$result = trim( $result );
		$result = trim( $result, '.' );
		$result = iconv( 'utf-8', 'windows-1251', $result );
		$result = $this->_makeFullPath( $result );
		$result .= '.txt';
		return $result;
	}

	private function _makeFullPath( $file )
	{
		$result = $this->getSavePath() . '/' . $file;
		return $result;
	}
}